//
//  HLCategoryViewModel.swift
//  HLXiMaLaYa
//
//  Created by hulinhu on 2018/1/29.
//  Copyright © 2018年 hulinhu. All rights reserved.
//

import UIKit
import RxDataSources
import NSObject_Rx
import RxSwift
import RxCocoa
import ObjectMapper

class HLCategoryViewModel: NSObject {
    
    //  单Section 存放着解析完成的模型数组  Variable<[Model]>([])
    //  多Section 数组内部 套 元祖 或者 数组
    private let vmDatas = Variable<[([HLCategoryItemModel]?)]>([])

}

extension HLCategoryViewModel : HLViewModelType {
    typealias Input = HLCategoryInput
    typealias Output = HLCategoryOutput
    
    // 输入
    struct HLCategoryInput {
        // 网络请求类型
        let category: HLRecommendNetManager.HLNetWorkStyleType
        
        init(category: HLRecommendNetManager.HLNetWorkStyleType) {
            self.category = category
        }
    }

    struct HLCategoryOutput {
        // tableView的sections数据
        let sections : Driver<[HLCategorySection]>
        // 外界通过该属性告诉viewModel加载数据（传入的值是为了标志是否重新加载）
        let requestCommand = PublishSubject<Bool>()
        // 重写
        init(sections: Driver<[HLCategorySection]>) {
            self.sections = sections
        }
    }

    func transform(input: HLCategoryViewModel.HLCategoryInput) -> HLCategoryViewModel.HLCategoryOutput {

        let temp_sections = vmDatas.asObservable().map {(sections) -> [HLCategorySection] in
            return sections.map({ (models) -> HLCategorySection in
                return HLCategorySection(items: models!)
            })
         }.asDriver(onErrorJustReturn: [])
  
        let output = HLCategoryOutput(sections: temp_sections)
        
        output.requestCommand.subscribe(onNext: { (data) in
            
            // MARK: - 提示
    //         HLProgressHUD.showSuccess("加载成功")
            
              var sectionArr: [([HLCategoryItemModel])] = []
        
                var subdict : [String : String]
                var titleArray : [[String: Any]] = []
                var modelArr : [HLCategoryItemModel] = []
            
                for _ in 0..<9 {
                    subdict = ["imageName":"cgz_ic_accuracy","titleName":"言情小说"]
                    titleArray.append(subdict)
                }
                 modelArr = Mapper<HLCategoryItemModel>().mapArray(JSONArray:titleArray)
                //  返回 多个Section
                 sectionArr.append(modelArr)
                 sectionArr.append(modelArr)
                 sectionArr.append(modelArr)
                 sectionArr.append(modelArr)
                 self.vmDatas.value = sectionArr

            }).disposed(by: rx.disposeBag)

            return output
        }
}

// MARK: - 结构体  数据结构
struct HLCategorySection {
    var items: [Item]
}

extension HLCategorySection: SectionModelType {
    
    typealias Item = HLCategoryItemModel
    init(original: HLCategorySection, items: [HLCategoryItemModel]) {
        self = original
        self.items = items
    }
}
